package com.tjshop.android.util;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.tjshop.android.model.Category;
import com.tjshop.android.model.CouponHomeData;
import com.tjshop.android.model.Coupons;
import com.tjshop.android.model.Promot;
import com.tjshop.android.model.keyPair;
import com.tjshop.android.model.tj.json.Banner;

/**
 * Json解析工具类
 * 
 * @author houzheng
 * 
 */
public class JsonParser {
	// 获取主页数据
	public static CouponHomeData getHomeData(String ret) {
		try {
			CouponHomeData homeData = new CouponHomeData();
			JSONObject json = new JSONObject(ret);
			if (json.getInt("code") == 0) {
				JSONObject data = json.getJSONObject("data");
				// 解析类别信息
				JSONArray categorys = data.getJSONArray("categories");
				for (int i = 0; i < categorys.length(); i++) {
					JSONObject item = categorys.getJSONObject(i);
					Category category = new Category();
					category.parse(item);
					homeData.addCategory(category);
				}
				if (homeData.getCategoryList().size() == 7) {
					Category more = new Category();
					more.setId("1000");
					// more.setIcon("test_more");
					// more.setSub_icon("test_more");
					homeData.addCategory(more);
				}
				// 解析Banner信息
				JSONArray banners = data.getJSONArray("banner_subject");
				for (int j = 0; j < banners.length(); j++) {
					JSONObject item = banners.getJSONObject(j);
					Banner banner = new Banner();
					banner.parse(item);
					homeData.addBanner(banner);
				}
				// 解析promo信息
				JSONArray promos = data.getJSONArray("promo_subject");
				for (int j = 0; j < promos.length(); j++) {
					JSONObject item = promos.getJSONObject(j);
					Promot promot = new Promot();
					promot.parse(item);
					homeData.addPromot(promot);
				}

				// 解析搜索关键字信息
				JSONArray keywords = data.getJSONArray("keywords_map");
				for (int k = 0; k < keywords.length(); k++) {
					homeData.addKeyWord(keywords.getString(k));
				}

				// 解析猜你喜欢信息
				JSONObject coupon_section = data
						.getJSONObject("coupon_section");
				JSONArray YouLikeList = coupon_section
						.getJSONArray("coupon_list");
				for (int j = 0; j < YouLikeList.length(); j++) {
					JSONObject subItems = YouLikeList.getJSONObject(j);
					Coupons sublistinfo = new Coupons();
					sublistinfo.parse(subItems);
					homeData.addCoupon(sublistinfo);
				}
				return homeData;
			} else {
				return null;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
}
